package team.pwy.redismessage;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import team.pwy.mapper.*;
import team.pwy.pojo.entity.Coupon;
import team.pwy.pojo.entity.Movie;
import team.pwy.pojo.entity.Order;
import team.pwy.pojo.entity.PwyViewingHistory;
import team.pwy.service.WebSocketProcess;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @title: RedisMessageReceiver
 * @author: DaiLing
 * @description: TODO
 * @date: 2024/2/5 10:27
 */
@Slf4j
public class KeyExpiredListener extends KeyExpirationEventMessageListener {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private MovieMapper movieMapper;

    @Resource
    private ViewingHistoryMapper viewingHistoryMapper;

    @Resource
    private MessageMapper messageMapper;

    @Resource
    private CouponMapper couponMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private WebSocketProcess webSocketProcess;

    public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * @author DaiLing
     * @description 监听redis过期key
     * @date 2024/2/5 16:22
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获得过期的key
        String[] key = message.toString().split(":");
        String keyName = key[0];
        String redisKey = message.toString();
        switch (keyName) {
            // 监听观影记录redis过期key
            case "lookOld" -> {
                List<Order> start = orderMapper.findStart(Integer.parseInt(key[1]));
                for (Order order : start) {
                    orderMapper.updateById(order.getId(), 4);
                    PwyViewingHistory pwyViewingHistory = new PwyViewingHistory();
                    pwyViewingHistory.setId(null);
                    pwyViewingHistory.setUserId(order.getUserId());
                    pwyViewingHistory.setMovieId(order.getMovieId());
                    pwyViewingHistory.setMovieTittle(order.getMovieTitle());
                    pwyViewingHistory.setPosterImg(order.getPosterImg());
                    Movie movie = movieMapper.findById(order.getMovieId());
                    pwyViewingHistory.setDirector(movie.getDirector());
                    pwyViewingHistory.setDuration(movie.getDuration());
                    pwyViewingHistory.setScore(movie.getScore());
                    pwyViewingHistory.setCreateTime(new Date());
                    viewingHistoryMapper.add(pwyViewingHistory);
                }
            }

            // 监听电影场次开场redis过期key
            case "sessionTip" -> {
                List<Order> start = orderMapper.findStart(Integer.parseInt(key[1]));
                for (Order order : start) {
                    String messageTip = "您购买的电影: {" + order.getMovieTitle() + "{还有不到两小时就放映啦!请提前到场以免错过放映时间,感谢您的观看!";
                    orderMapper.updateById(order.getId(), 3);
                    team.pwy.pojo.entity.Message message1 = new team.pwy.pojo.entity.Message();
                    message1.setUserId(order.getUserId());
                    message1.setStatus(1);
                    message1.setMessage(messageTip);
                    message1.setCreateTime(new Date());
                    message1.setType(2);
                    messageMapper.addMessage(message1);
                    try {
                        webSocketProcess.sendMessagezf(order.getUserId(), messageTip);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }

            // 监听优惠卷即将过期 redis过期key
            case "couponNext" -> {
                int userId = (int) redisTemplate.opsForValue().get(redisKey);
                // 优惠券过期
                Coupon coupon = couponMapper.findByCouponId(Integer.valueOf(key[1]));
                Date now = coupon.getUpdatedBy();
                // 指定格式化格式
                SimpleDateFormat f = new SimpleDateFormat("yyyy 年 MM 月 dd 日 E HH 点 mm 分 ss 秒");

                String messageCoupon = "您有一张{" + coupon.getMoney() + "{元的优惠券即将在{" + f.format(now) + "{后过期,请及时使用!";

                team.pwy.pojo.entity.Message message1 = new team.pwy.pojo.entity.Message();
                message1.setUserId(userId);
                message1.setStatus(1);
                message1.setMessage(messageCoupon);
                message1.setCreateTime(new Date());
                message1.setType(0);

                messageMapper.addMessage(message1);
                try {
                    webSocketProcess.sendMessagezf(userId, messageCoupon);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

            // 监听优惠卷过期 redis过期key
            case "couponEnd" -> {
                int userId = (int) redisTemplate.opsForValue().get(redisKey);
                int couponId = Integer.parseInt(key[1]);
                Coupon coupon = couponMapper.findByCouponId(couponId);
                couponMapper.updateByCouponId(2, couponId);
                String messageCouponEnd = "您的{" + coupon.getMoney() + "{元优惠券已过期";
                team.pwy.pojo.entity.Message message1 = new team.pwy.pojo.entity.Message();
                message1.setUserId(userId);
                message1.setStatus(1);
                message1.setMessage(messageCouponEnd);
                message1.setCreateTime(new Date());
                message1.setType(1);
                messageMapper.addMessage(message1);
                try {
                    webSocketProcess.sendMessagezf(userId, messageCouponEnd);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
